'use strict'

/**
 * 为简单，不适用任何日志库，直接使用console.log
 */

const _join = Array.prototype.join;
function _leftpad (str, _len, ch) {
  str = String(str);
  if (!ch && ch !== 0) ch = ' ';
  let len = _len - (str.length -1);
  return _join.call({
    length: len
  }, ch)+str;
}

/**
 * 获取前缀日志格式
 * @param {string} extra
 * @return {string}
 */
function makeLogPrefix(extra) {
  let dat = new Date();// 生成日期
  let year = dat.getFullYear();// 取得年
  let month = _leftpad(dat.getMonth()+1, 2, '0'); // 取得月,js从0开始取,所以+1
  let date1 = _leftpad(dat.getDate(), 2, '0'); // 取得天
  let hour = _leftpad(dat.getHours(), 2, '0');// 取得小时
  let minutes = _leftpad(dat.getMinutes(), 2, '0');// 取得分钟
  let second = _leftpad(dat.getSeconds(), 2, '0');// 取得秒
  let haomiao = _leftpad(dat.getMilliseconds(), 3, '0');
  dat = undefined;
  return year+'-'+month+'-'+date1+' '+hour+':'+minutes +':'+second+'.'+haomiao + extra;
}

console.oldlog = console.log;
console.oldtrace = console.trace;
console.oldwarn = console.warn;
console.olderror = console.error;
console.oldinfo = console.info;

/**
 * log
 */
function log(...args) {
  process.stdout.write(makeLogPrefix('[log]: '));
  console.oldlog(...args);
}

/**
 * trace
 */
function trace(...args) {
  process.stdout.write(makeLogPrefix('[trace]: '));
  console.oldtrace(...args);
}

/**
 * info
 */
function info(...args) {
  process.stdout.write(makeLogPrefix('[info]: '));
  console.oldinfo(...args);
}

/**
 * warn
 */
function warn(...args) {
  process.stderr.write(makeLogPrefix('[warn]: '));
  console.oldwarn(...args);
}

/**
 * error
 */
function error(...args) {
  process.stderr.write(makeLogPrefix('[error]: '));
  console.olderror(...args);
}


module.exports = {
  overwrite: function(console) {
    console.log = log;
    console.trace = trace;
    console.info = info;
    console.warn = warn;
    console.error = error;
  },
  makeLogPrefix,
};